package com.faxsun.controller.uc.entity;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.LogFactory;
import org.broadleafcommerce.profile.core.domain.Customer;
import org.broadleafcommerce.profile.core.service.CustomerService;
import org.springframework.stereotype.Component;

import com.faxsun.profile.core.service.FSThirdPartyCustomerService;

import weibo4j.Account;
import weibo4j.Oauth;
import weibo4j.Users;
import weibo4j.http.AccessToken;
import weibo4j.model.User;
import weibo4j.model.WeiboException;
import weibo4j.org.json.JSONException;
import weibo4j.org.json.JSONObject;

@Component
public class Weibo extends ThirdPartyLoginAbs {
	private static final org.apache.commons.logging.Log log = LogFactory
			.getLog(Weibo.class);

	@Resource(name = "fsThirdPartyService")
	ThirdPartyLoginServer loginServer;

	@Resource(name = "blCustomerService")
	CustomerService customerService;
	
	@Resource(name = "blThirdPartyCustomerService")
	FSThirdPartyCustomerService fscustomer3thService;

	@Override
	public String login(ThirdPartyObj obj) {
		if (obj.getUid() == null || obj.getUid().isEmpty()) {
			return HOME; // Auth Login Failed! Inform, HOME---> FAIL Page
		}
		if(fscustomer3thService.checkCustomerBy3thUid(obj.getUid())){	
			Customer customer = fscustomer3thService.getCustomerByUid(obj.getUid());
			loginServer.loginDirectly(customer);
			return HOME;
		} else {
			return loginServer.registerThenLogin(obj.getNickName(),
					obj.getUid(), obj.getChannelId(),obj.getAvatar(),null);
		}
	}
	

	@Override
	public ThirdPartyObj get3rdObj(HttpServletRequest request,
			HttpServletResponse response, String channel, String path) {
		ThirdPartyObj obj3rd = new ThirdPartyObj();
		obj3rd.setChannelId(channel);
		Oauth oauth2 = new Oauth();
		AccessToken accessTokenObj = null;
		obj3rd.setCode(request.getParameter("code"));
		try {
			accessTokenObj = oauth2.getAccessTokenByCode(obj3rd.getCode());
			if (accessTokenObj.getAccessToken().equals("")) {
				// 我们的网站被CSRF攻击了或者用户取消了授权
				// 做一些数据统计工作
				// System.out.print(“没有获取到响应参数”);
				log.info("授权被取消");
			} else {
				obj3rd.setAccessToken(accessTokenObj.getAccessToken());
				
				String accessToken = accessTokenObj.getAccessToken() ;
				HttpSession session = request.getSession();
				session.setAttribute("accessToken", accessToken);
				
				Account account = new Account(obj3rd.getAccessToken());
				JSONObject uidJson = account.getUid();
				obj3rd.setUid(uidJson.getString("uid"));
				Users users = new Users(obj3rd.getAccessToken());
				User weiboUser = users.showUserById(obj3rd.getUid());
				obj3rd.setNickName(weiboUser.getScreenName());
			}
		} catch (WeiboException e) {
			log.error("Weibo access token error ", e);
			e.printStackTrace();
		} catch (JSONException e) {
			log.error("json parse from access token error", e);
			e.printStackTrace();
		}
		return obj3rd;
	}

	@Override
	public void ResponseURL(HttpServletRequest request,
			HttpServletResponse response) {
		Oauth oauth = new Oauth();
		try {
			String url = oauth.authorize("code");
			response.sendRedirect(url);
		} catch (WeiboException e) {
			log.error("Weibo authorize error ", e);
			e.printStackTrace();
		} catch (IOException e) {
			log.error("Weibo response sendRedirect error ", e);
			e.printStackTrace();
		}
	}

	// NOT Working
	public void logout(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session=request.getSession();
		String accessToken = (String) session.getAttribute("accessToken");
		if(accessToken != null && !accessToken.isEmpty()){
			Account am = new Account(accessToken);
			try {
				User user = am.endSession();
				log.info(user.toString()+"logout");
			} catch (WeiboException e) {
				e.printStackTrace();
			}
		}	
	};

}
